package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.entity.Foot;
import com.example.entity.Product;
import com.example.entity.User;
import com.example.mapper.FootMapper;
import com.example.mapper.ProductMapper;
import com.example.service.IFootService;
import com.example.service.IUserService;
import com.example.utils.Result;
import com.example.vo.FootVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 * @author cyz
 * @since 2022-06-19
 */
@Service
public class FootServiceImpl extends ServiceImpl<FootMapper, Foot> implements IFootService {

    @Autowired
    private IUserService userService;

    @Autowired
    private FootMapper footMapper;

    @Autowired
    private IFootService footService;

    @Autowired
    private ProductMapper productMapper;

    @Override
    public Result saveFoot(String token, Integer productId) {
        User check = userService.check(token);
        LambdaQueryWrapper<Foot> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Foot::getProductId,productId);
        queryWrapper.eq(Foot::getUserId,check.getId());
        Foot foot = footMapper.selectOne(queryWrapper);
        if (foot!=null){
            footMapper.update(foot,queryWrapper);
            return Result.success("浏览记录成功1");
        }
        Foot newFoot = new Foot();
        newFoot.setUserId(check.getId());
        newFoot.setProductId(productId);
        boolean save = footService.save(newFoot);
        if (save){
            return Result.success("浏览记录成功");
        }else {
            return Result.fail(400,"浏览记录失败");
        }

    }

    @Override
    public Result getListByUser(Integer userId) {
        LambdaQueryWrapper<Foot> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Foot::getUserId,userId);
        queryWrapper.orderByDesc(Foot::getUpdateTime);
        List<Foot> footList = footMapper.selectList(queryWrapper);
        ArrayList<FootVo> FootVoList = new ArrayList<>();
        for (Foot foot : footList) {
            Product product = productMapper.selectById(foot.getProductId());
            FootVo footVo = new FootVo();
            BeanUtils.copyProperties(product,footVo);
            BeanUtils.copyProperties(foot,footVo);
            FootVoList.add(footVo);
        }
        return Result.success(FootVoList);
    }


}
